// pages/function/sub/tab-list-search.js
const APP = getApp();
//常量
const HISTORY_KEY = 'history_key_2021';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    //固定参数
    dataEmptyImg: '/asset/img/empty/icon_list_empty.png',
    dataEmptyTip:'暂无数据',
    //布局参数
    scrollviewHeight:0,
    //分页变量
    listContainerId: 'fwcontainer-id',
    tabsCurrentIndex:0,
    tabsTitle:[
      { title: 'Tab标题1' },
      { title: 'Tab标题2' },
      { title: 'Tab标题3' }
    ],
    tabsList: [],
    tabsPagenum: [],
    tabsTotalpage: [],
    tabsScrollViewPulldown:[],
    //逻辑变量
    dataKeywords:'',
    dataTags:[],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let _this = this;

    //控制权限
    APP.appauth.setAuthSetting();
    //重置数据
    this.setTabDefaultValue();    
    //  高度自适应
    APP.apptool.setAutoSize(function(res,sysRes){
      // res结构{cwidth, cheight, rpxRate, pixelRatio}
      _this.setData({
        scrollviewHeight: res.cheight - 100
      });
    });
    //显示预设路径
    _this.navigateNextPage();

    if(options.keywords){
      _this.setData({
        dataKeywords:options.keywords
      });
    }
    //加载关键词
    _this.loadHistoryTag();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let _this = this;
    //加载布局
    _this.initLayout();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    let _this = this;

    //同步上页的关键词
    let pages = getCurrentPages();
    let previous = pages[pages.length-2];
    previous.refreshData(_this.data.dataKeywords);
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    let _this = this;
    _this.loadResetList(function(){
      wx.stopPullDownRefresh();
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let _this = this;
    if (_this.data.tabsPagenum[_this.data.tabsCurrentIndex] < _this.data.tabsTotalpage[_this.data.tabsCurrentIndex]) {
      _this.loadPageList(null);
    } else {
      wx.showToast({
        title: '已经是最后一页了',
        icon: 'none',
        duration: 2000
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  /**
   * 逻辑区域
   */

  //初始布局
  initLayout: function () {
    let _this = this;

    try {
      var value = wx.getStorageSync('switch_index')
      if (value) {
        let jsonParam = APP.apptool.decodeJsonStr(value);
        //清除定位符
        try {
          wx.removeStorageSync('switch_index');
        } catch (e) {}
        
        let tabsIndex = jsonParam.tabIdx;
        if(-1 != tabsIndex){
          _this.setData({
            tabsCurrentIndex: tabsIndex
          },function(){
            //加载数据(过滤Tabs切换事件冲突情况)
            if (_this.data.tabsCurrentIndex == 0){
              this.loadPageData();
            }
          });
        }
      }else{
        _this.loadPageData();
      }
    } catch (e) {
      APP.applog.error(e);
    }
  },

  //加载界面数据
  loadPageData: function () {
    let _this = this;
    _this.loadPageList(null);
  },

  //加载列表数据
  loadPageList: function (completedcallback) {
    let _this = this;
    APP._post('/miniprogram/NavLayout/listMulti', {
      caPageIndex: _this.data.tabsPagenum[_this.data.tabsCurrentIndex] + 1,
      tab_idx:_this.data.tabsCurrentIndex,
      keyword:_this.data.dataKeywords,
    }, null, function (res) {
      //执行成功
      if (res.caCode === APP.appconfig.fwcode.successed) {
        let resData = res.caData;
        _this.setData({
          ['tabsPagenum[' + _this.data.tabsCurrentIndex + ']']: _this.data.tabsPagenum[_this.data.tabsCurrentIndex] + 1,
          ['tabsTotalpage[' + _this.data.tabsCurrentIndex + ']']: resData.caPageTotal,
          ['tabsList[' + _this.data.tabsCurrentIndex + ']']: _this.data.tabsList[_this.data.tabsCurrentIndex].concat(resData.caPageList)
        })
      } else {
        APP.apptool.showToastInfo(res.caMsg);
      }
    }, function (res) {
      //执行失败
    }, function (res) {
      //执行完成
      completedcallback && completedcallback();
    });
  },

  //重置数据
  loadResetList: function (completedcallback){
    let _this = this;

    //重置列表数据
    _this.setData({
      ['tabsList[' + _this.data.tabsCurrentIndex + ']']: [],
      ['tabsPagenum[' + _this.data.tabsCurrentIndex + ']']: 0,
      ['tabsTotalpage[' + _this.data.tabsCurrentIndex + ']']: 1,
      ['tabsScrollViewPulldown[' + _this.data.tabsCurrentIndex + ']']: false
    }, function () {
      _this.loadPageList(completedcallback);
    });
  },

  //TabTitles切换事件
  switchTab: function (event) {
    let currentIndex = event.currentTarget.dataset.idx;
    if (this.data.tabsCurrentIndex != currentIndex) {
      this.setData({
        tabsCurrentIndex: currentIndex
      });
    }
  },

  //Tabs切换触发事件(只要tabsCurrentIndex!=0就会触发该事件)
  switchTabView: function (event) {
    let _this = this;
    let currentIndex = event.detail.current;
    _this.setData({
      tabsCurrentIndex: currentIndex
    });
    //限制首次加载
    if (_this.data.tabsPagenum[_this.data.tabsCurrentIndex] == 0) {
      _this.loadPageList(null);
    }
  },

  //设置默认值
  setTabDefaultValue: function () {
    for (let i = 0; i < this.data.tabsTitle.length; i++) {
      this.data.tabsPagenum.push(0);
      this.data.tabsTotalpage.push(1);
      this.data.tabsList.push([]);
      this.data.tabsScrollViewPulldown.push(false);
    }
  },

  //scroll-view下拉顶部事件
  onScrollViewPullDown:function(event){
    let _this = this;

    _this.loadResetList(function(){
      _this.setData({
        ['tabsScrollViewPulldown[' + _this.data.tabsCurrentIndex + ']']: false
      });
    });
  },

  //scroll-view滚动底部事件
  onScrollViewReachBottom:function(event){
    this.onReachBottom();
  },

  //跳转路径
  navigateNextPage: function () {
    let navPath = APP.globalData.navigatePath;
    APP.apptool.navigateNextPage(navPath, function (isLastOne) {
      if (isLastOne) {
        //清除预设路径
        APP.globalData.navigatePath = '';
      }
    });
  },

  //回调刷新数据
  refreshPage: function(){
    this.onPullDownRefresh();
  },

  //空图显示占位图
  bindTabImageListError: function (eventhandle) {
    APP.apptool.bindTabImageListError(eventhandle, this);
  },

  //查看详情
  clickView: function(event){
    let _this = this,dataset = event.currentTarget.dataset;

    APP.apptool.showToastInfo('数据编号：'+dataset.id);
    // wx.navigateTo({
    //   url: '/pages/course/sub/list?tid='+dataset.id,
    // });
  },

  //回调刷新数据
  refreshPage: function(){
    this.onPullDownRefresh();
  },

  //查询
  doSearch:function(event){
    let _this = this,isHad = false;
    
    _this.setData({
      dataKeywords:event.detail.value,
    },function(){
      for(let i=0; i<_this.data.dataTags.length; i++){
        if(_this.data.dataKeywords == _this.data.dataTags[i]){
          isHad = true;
          break;
        }
      }
      if(!isHad){
        // _this.data.dataTags.push(_this.data.dataKeywords);
        _this.data.dataTags.unshift(_this.data.dataKeywords);
        _this.syncHistoryTag();
      }
      //加载数据
      _this.setTabDefaultValue(function(){
        _this.loadPageData(null);
      });
    });
  },
  //数据处理
  syncHistoryTag:function(){
    let _this = this;

    wx.setStorage({
      key:HISTORY_KEY,
      data:_this.data.dataTags,
      success (res) {}
    });
  },
  loadHistoryTag:function(){
    let _this = this;

    wx.getStorage({
      key:HISTORY_KEY,
      success (res) {
        _this.setData({
          dataTags:res.data
        });
      }
    });
  }
})